/*  This file is part of -_-.

    -_- is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    -_- is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with -_-.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2012-2013 Oliver Katz */

#include "macro.h"

namespace sleepyface
{
    namespace opal
    {
        FunctionalMacro::FunctionalMacro()
        {
        }

        FunctionalMacro::FunctionalMacro(string s, AST m)
        {
            symbol = s;
            macro = m;
        }

        int FunctionalMacro::addArgument(string a)
        {
            arguments.push_back(a);
            return 0;
        }

        string FunctionalMacro::getArgument(int idx)
        {
            return arguments[idx];
        }

        int FunctionalMacro::size()
        {
            return arguments.size();
        }

        AST FunctionalMacro::evaluateArguments(AST ast, map<string, AST> args)
        {
            if (ast.isLeaf() && args.find(ast.get().get()) != args.end())
                return args[ast.get().get()];
            AST tmp = AST(ast.get());
            for (vector<AST>::iterator i = ast.getBranches().begin(); i != ast.getBranches().end(); i++)
                tmp.branch(evaluateArguments(*i, args));
            return tmp;
        }

        AST FunctionalMacro::evaluate(AST src, map<string, AST> args)
        {
            AST tmp = AST(Token(symbol, src.get().getLine(), src.get().getColumn()));
            AST e = evaluateArguments(src, args);
            for (vector<AST>::iterator i = e.getBranches().begin(); i != e.getBranches().end(); i++)
                tmp.branch(*i);
            return tmp;
        }
    }
}
